<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>js 实现屏幕录制</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
  </head>
  <body>
  <p>
    突然发现只能录制视频但是无法录制声音
    目标自己实现声音的录制
  </p>
   <video src="" width="600px"  controls> </video>
 
   <button class="record-btn">record</button>
    
  </body>
  <script>
     // js 实现屏幕录制 webTC 的一部分
     //  接口 MediaDevices.getDisplayMedia() 与 MediaRecorder  接口
   
     let btn = document.querySelector('.record-btn')
     let video = document.querySelector('video')
     let mediaRecorder;

     btn.addEventListener('click', async function(){
        // 拿到媒体录制流
         let stream = await navigator.mediaDevices.getDisplayMedia({
           video:true,
           audio:true,
         })
         // 直接将getDisplayMedia 传给video,这时候得用scrObject 
        //  video.srcObject = stream
    
        stream.getVideoTracks()[0].onended = async ()=>{
          //单击停止共享按钮后，触发这个事件
          console.log('stop') 
        }


      //  浏览器支持的视频格式
      const  mime = MediaRecorder.isTypeSupported("video/webem; codecs=vp9")
                  ? "video/webm; codecs=vp9"
                  : "video/webm"

       mediaRecorder = new MediaRecorder(stream,{ 
                mimeType:mime,
        })
      // let mediaRecorder = new MediaRecorder(stream)

      // 将数据 存入数组
      let chunks =[];
      mediaRecorder.addEventListener('dataavailable',function(e){
        console.log('dataavailable') 
        chunks.push(e.data)
   
       
        

      })
     
      // 结束录制时候,会触发dataavailable 事件，返回一个存储Blob内容的录制数据.之后不再记录
      mediaRecorder.addEventListener('stop',function(){
        console.log('stop') 
        // let blob = new Blob(chunks,{
        //    type:chunks[0].type
        //   })   
        // let url = URL.createObjectURL(blob)

        
        
        // video.src= url
           
          // let a = document.createElement('a')
          // a.href = url
          // a.download = 'video/webm'
          // a.click()
      })

     console.log('开始录制')
     // 必须手动启用
       mediaRecorder.start()


     })




  </script>
</html>